//指定中文输出编码
phantom.outputEncoding="GBK";

var fs = require('fs');

var casper = require('casper').create({
	clientScripts:[
		'jquery-2.2.4.min.js'
	]
});

var url = "http://app.finance.ifeng.com/hq/list.php";
var allStocks = {};

function getStocks(){
	var list = [];
	$('div.result ul li a').each(function(i,item){
		var text = $(item).text();
		var stock_name = text.substring(0,text.indexOf('('));
		var stock_code = text.substring(text.indexOf('(')+1,text.indexOf(')'));
		var stock = {};
		stock["code"] = stock_code;
		stock["name"] = stock_name;
		list.push(stock);
	});
	return list;
}

//浏览list页面
casper.start(url);

//HA
var ha = [];
casper.thenOpen(url + '?type=stock_a&class=ha',function(){
	ha = this.evaluate(getStocks);
	allStocks["ha"] = ha;
});

//SA
var sa = [];
casper.thenOpen(url + '?type=stock_a&class=sa',function(){
	sa = this.evaluate(getStocks);
	allStocks["sa"] = sa;
});

//GEM
var gem = [];
casper.thenOpen(url + '?type=stock_a&class=gem',function(){
	gem = this.evaluate(getStocks);
	allStocks["gem"] = gem;
});

//写入文件
casper.then(function(){
	var data = JSON.stringify(allStocks);
	fs.write('all_stocks.txt',data,'w');
});

casper.run();